package _15_generics._15_8.exercise;

import java.lang.reflect.Constructor;

/**
 * Use a type tag along with reflection to create
 * a method that uses the argument version of
 * newInstance() to create an object of a class
 * with a constructor that has arguments
 */
public class E22_InstantiateGenericType2 {
}

class ClassAsFactory<T> {
    Class<T> kind;

    public ClassAsFactory(Class<T> kind) {
        this.kind = kind;
    }

    public T create(int arg) {
        try {
            for (Constructor<?> ctor : kind.getConstructors()) {
                Class<?>[] params = ctor.getParameterTypes();
                if (params.length == 1 && params[0] == int.class){
                    return kind.cast(ctor.newInstance(arg));
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return null;
    }
}
